package com.bi.cloud.config;

import com.bi.cloud.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

@Configuration
public class JwtTokenConfig {

    @Value("${pubPath}")
    private String pubPath;

    //公钥缓存key值,必须唯一
    @Value("${redis_key}")
    private  String PUBLIC_KEY;

    @Resource
    private RedisTemplate redisTemplate;


    @Bean
    public TokenStore jwtTokenStore() throws Exception {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() throws Exception {
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        accessTokenConverter.setVerifierKey(getPublicKey(pubPath));
       // accessTokenConverter.setSigningKey("admin-sign");
        return accessTokenConverter;
    }

    /**
     * 从redis中获取公钥
     */
    public  String getPublicKey(String path) throws Exception {

        String key = (String) redisTemplate.opsForValue().get(PUBLIC_KEY);
        if(StringUtils.isEmpty(key)){
            key = RSAUtils.getPubKey(path);
            if(!StringUtils.isEmpty(key)){
                redisTemplate.opsForValue().set(PUBLIC_KEY,key);
            }
        }
        //String key = RSAUtils.getPubKey(path);
        return key;
    }
}
